from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import OAAbstractUser,UserStatusChoices,OADepartment
from .serializers import LoginSerializer,CustomTokenObtainPairSerializer,UserSerializer,DeptSerializer
from datetime import datetime
from rest_framework.permissions import IsAuthenticated, IsAdminUser,AllowAny
from rest_framework import status
from rest_framework import viewsets
from apps.absent.page import MyModelPagination
from rest_framework_simplejwt.views import TokenObtainPairView


# 获取jwt的token，继承自TokenObtainPairView
class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

class LoginView(APIView):
    permission_classes = [AllowAny]
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            user.last_login = datetime.now()
            user.save()
            # 获取生成的 token
            access_token = serializer.validated_data['access_token']
            refresh_token = serializer.validated_data['refresh_token']

            return Response({
                'access_token': access_token,
                'refresh_token': refresh_token,
                'user': UserSerializer(user).data
            })
        else:
            print(serializer.errors)
            return Response({'detail': '参数错误'}, status=status.HTTP_400_BAD_REQUEST)


class DeptView(viewsets.ModelViewSet):
    queryset = OADepartment.objects.all()
    serializer_class = DeptSerializer

#修改密码
class ChangePasswordView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')
        confirm_password = request.data.get('confirm_password')

        if not old_password or not new_password or not confirm_password:
            return Response({'detail': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)

        if new_password != confirm_password:
            return Response({'detail': '两次输入的新密码不一致'}, status=status.HTTP_400_BAD_REQUEST)

        if not user.check_password(old_password):
            return Response({'detail': '旧密码错误'}, status=status.HTTP_400_BAD_REQUEST)

        user.set_password(new_password)
        user.save()

        return Response({'detail': '密码修改成功'}, status=status.HTTP_200_OK)


